interface storeKey {
    [propName: string]: any
}

class Store {
    private storage: storeKey = {};

    /**
     * 存储数据 （未使用redis）
     * @param name
     * @param value
     * @param expire 默认存储七天
     */
    set(name: string, value: any, expire: number = 3600 * 24 * 7) {
        this.storage[name] = JSON.stringify({
            value,
            expire: expire !== null ? new Date().getTime() + expire : null,
        })
    }

    get(name: string) {
        const item = this.storage[name];
        if (item !== null) {
            try {
                const data = JSON.parse(item);
                if (data.expire === null) {
                    return data.value;
                }
                if (data.expire >= new Date().getTime()) {
                    return data.value;
                }
                delete this.storage[name]
            } catch (err) {
                return null;
            }
        }
        return null;
    }

    setCookie(cookies: Array<string>) {
        if (!cookies || cookies.length === 0) {
            return
        }
        for (let i = 0; i < cookies.length; i++) {
            let cookie: string | null = cookies[i];
            if (cookie != null && cookie != "") {
                let res: RegExpMatchArray | null = cookie.match(/(.+?)=(.+?);/);
                if (res && res.length == 3) {
                    const key: string = res[1];
                    this.set(key, res[2])
                }
            }
        }
    }

    getCookies(): string {
        return Object.keys(this.storage).reduce((c, key) => {
            let val = this.get(key);
            if (!val) return c;
            return c + `${key}=${val};`;
        }, "")
    }
}

const getSingleInstance = (function () {
    let instance: Store | null = null;
    return function () {
        if (instance == null) {
            instance = new Store();
        }
        return instance;
    };
})();

export default getSingleInstance();